<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>报修管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;

        }

        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .title {
            font-size: 20px;
            font-weight: bold;
        }

        .search-box {
            display: flex;
            align-items: center;
        }

        .search-box input {
            margin-right: 10px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .button-group {
            display: flex;
        }

        .button-group button {
            margin-left: 10px;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .query-btn {
            background-color: #4CAF50;
            color: white;
        }

        .add-btn {
            background-color: #2196F3;
            color: white;
        }

        .export-btn {
            background-color: #9E9E9E;
            color: white;
        }

        .table-container {
            background-color: white;
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f5f5f5;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .action-buttons button {
            padding: 4px 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            color: white;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .process-btn {
            background-color: orange;
        }

        .complete-btn {
            background-color: #4CAF50;
        }

        .withdraw-btn {
            background-color: #f44336;
        }

        .pagination {
            text-align: center;
            margin-top: 15px;
            color: #666;
        }
    </style>
</head>
<body>
<div class="container">
    <form>
        <div class="header">
            <div class="title">报修管理</div>
            <div class="search-box">
                <input type="text" id="orderId" name="orderId" placeholder="报修单号">
                <input type="text" id="roomNumber" name="roomNumber" placeholder="宿舍号">
            </div>
            <div class="button-group">
                <button type="button" class="query-btn" onclick="loadData()">
                    <svg t="1746532550209" class="icon" viewBox="0 0 1024 1024" version="1.1"
                         xmlns="http://www.w3.org/2000/svg" p-id="2629" width="15" height="15">
                        <path d="M747.95000029 667.43l197.39999971 197.39999971a56.90999971 56.90999971 0 0 1-80.52000029 80.49000058l-197.39999971-197.40000058a378.29999971 378.29999971 0 0 1-225.42000029 74.10000058C232.1 821.98999971 62 651.83000029 62 441.98 62 232.1 232.12999971 62 442.00999971 62c209.85000029 0 379.98 170.12999971 379.98 380.00999971a378.29999971 378.29999971 0 0 1-74.03999942 225.42000029z m-305.94000058 40.70999971a266.15999971 266.15999971 0 1 0 0-532.28999971 266.15999971 266.15999971 0 0 0 0 532.28999971z"
                              p-id="2630" fill="#ffffff"></path>
                    </svg>
                    查询
                </button>
                <button class="add-btn">
                    <svg t="1746533128195" class="icon" viewBox="0 0 1066 1024" version="1.1"
                         xmlns="http://www.w3.org/2000/svg" p-id="22530" width="15" height="15">
                        <path d="M405.333333 533.333333C275.925333 533.333333 170.666667 428.032 170.666667 298.666667s105.258667-234.666667 234.666666-234.666667S640 169.301333 640 298.666667s-105.258667 234.666667-234.666667 234.666666z m0-341.333333C346.538667 192 298.666667 239.829333 298.666667 298.666667s47.872 106.666667 106.666666 106.666666S512 357.504 512 298.666667s-47.872-106.666667-106.666667-106.666667z"
                              fill="#ffffff" p-id="22531"></path>
                        <path d="M405.333333 960C283.477333 960 0 945.450667 0 810.666667c0-223.488 181.845333-405.333333 405.333333-405.333334S810.666667 587.178667 810.666667 810.666667c0 134.784-283.477333 149.333333-405.333334 149.333333z m-276.693333-168.021333c32.725333 16.469333 129.834667 40.021333 276.693333 40.021333s243.968-23.552 276.693334-40.021333C672.384 647.722667 551.978667 533.333333 405.333333 533.333333s-267.050667 114.389333-276.693333 258.645334zM1002.666667 362.666667h-256a64 64 0 1 1 0-128h256a64 64 0 1 1 0 128z"
                              fill="#ffffff" p-id="22532"></path>
                        <path d="M874.666667 490.666667A64 64 0 0 1 810.666667 426.666667V170.666667a64 64 0 1 1 128 0v256a64 64 0 0 1-64 64z"
                              fill="#ffffff" p-id="22533"></path>
                    </svg>
                    新增报修
                </button>
                <button class="export-btn" onclick="exportReport()">
                    <svg t="1746533309510" class="icon" viewBox="0 0 1024 1024" version="1.1"
                         xmlns="http://www.w3.org/2000/svg" p-id="23593" width="15" height="15">
                        <path d="M882.816 341.632L618.816 77.632c-11.2-11.2-26.432-13.248-42.048-13.248H144a16 16 0 0 0-16 16V944c0 8.832 7.168 16 16 16h736a16 16 0 0 0 16-16V383.232c0-15.232-1.984-30.464-13.184-41.6zM608 157.184L802.816 352H608V157.184zM832 896H192V128h352v272c0 8.832 7.168 16 16 16H832V896z"
                              fill="#ffffff" p-id="23594"></path>
                        <path d="M400 518.784a16 16 0 0 0-22.784 0l-22.848 22.848a16 16 0 0 0 0 22.784l109.632 108.8-109.184 109.184a16 16 0 0 0 0 22.784l22.784 22.848a16 16 0 0 0 22.784 0l109.248-109.248 109.184 109.248a16 16 0 0 0 22.784 0l22.784-22.848a16 16 0 0 0 0-22.784l-109.184-109.184 108.416-109.248a16 16 0 0 0 0-22.784l-22.848-22.784a16 16 0 0 0-22.784 0l-108.8 109.632L400 518.72z"
                              fill="#ffffff" p-id="23595"></path>
                    </svg>
                    导出
                </button>
            </div>
        </div>
    </form>
    <div class="table-container">
        <table id="adminTable">
            <thead>
            <tr>
                <th>报修单号</th>
                <th>宿舍号</th>
                <th>报修人</th>
                <th>报修内容</th>
                <th>报修时间</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>

    <div class="pagination">
        <button class="btn-prev" onclick="loadData(currentPage-1)">上一页</button>
        <span id="pageInfo">第 1 页</span>
        <button class="btn-next" onclick="loadData(currentPage+1)">下一页</button>
    </div>
</div>
</div>

<!-- 优化后的新增报修模态框 -->
<div id="repairModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">新增报修</h2>
            <span class="close" onclick="closeModal()">&times;</span>
        </div>
        <form id="repairForm">
            <div class="form-group">
                <label for="modalRoomNumber">宿舍号</label>
                <input type="text" id="modalRoomNumber" name="roomNumber" placeholder="请输入宿舍号" required>
            </div>
            <div class="form-group">
                <label for="modalName">报修人</label>
                <input type="text" id="modalName" name="name" placeholder="请输入报修人姓名" required>
            </div>
            <div class="form-group">
                <label for="modalDescription">报修内容</label>
                <textarea id="modalDescription" name="description" placeholder="请详细描述报修问题" required></textarea>
            </div>
            <button type="button" class="submit-btn" onclick="submitRepair()">提交报修</button>
        </form>
    </div>
</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>

    function exportReport() {
        if($('#adminTable tbody tr').length === 0){
            alert("没有数据可以导出");
            return;
        }
        const wb = XLSX.utils.table_to_book(document.getElementById("adminTable"));
        const filename = "宿管信息.xlsx";
        XLSX.writeFile(wb, filename);

    }


    // 全局变量存储当前页码
    var currentPage = 0;
    var totalPages = 1;

    // 加载数据函数
    function loadData(page) {
        var orderId = $("#orderId").val();
        var roomNumber = $("#roomNumber").val();
        currentPage = page || 0;

        // 确保页码不小于0
        if (currentPage < 0) {
            currentPage = 0;
        }

        $.get("<%=request.getContextPath()%>/repairController", {
            op: "query",
            orderId: orderId,
            roomNumber: roomNumber,
            page: currentPage
        }, function (data) {
            updateTable(data);
        });
    }

    // 更新表格数据
    function updateTable(data) {
        var jsonData = JSON.parse(data);
        var html = "";

        $.each(jsonData.list, function (index, repair) {
            let actionBtns = "";
            if (repair.status === '待处理') {
                actionBtns += '<td><div class="action-buttons">' +
                    '<button class="process-btn">处理</button>' +
                    '<button class="withdraw-btn">撤回</button>' +
                    '</div></td>';
            } else if (repair.status === '处理中') {
                actionBtns += '<td><div class="action-buttons">' +
                    '<button class="complete-btn">完成</button>' +
                    '<button class="withdraw-btn">撤回</button>' +
                    '</div></td>';
            }
            
            html += '<tr>' +
                '<td onclick="goToEvaluation(\'' + repair.orderId + '\',\'' + repair.description + '\',\'' + repair.createdAt + '\',\'' + repair.status + '\')">' + repair.orderId + '</td>' +
                '<td>' + repair.roomNumber + '</td>' +
                '<td>' + repair.name + '</td>' +
                '<td>' + repair.description + '</td>' +
                '<td>' + repair.createdAt + '</td>' +
                '<td onclick="viewRepairProgress(\'' + repair.orderId + '\',\'' + repair.roomNumber + '\',\'' + repair.createdAt + '\',\''+  repair.processAt + '\',\''+ repair.completedAt + '\',\'' + repair.description +'\',\'' + repair.status+ '\')" class="status-' + (repair.status === '已完成' ? 'completed' : repair.status === '处理中' ? 'processing' : 'pending') + '">' + repair.status + '</td>' +
                actionBtns +
                '</tr>';
        });
        $("tbody").html(html);
        // 更新分页信息
        currentPage = jsonData.page;
        totalPages = jsonData.totalPages;
        $("#pageInfo").text("第 " + (currentPage + 1) + " 页/共 " + totalPages + " 页");
        $(".btn-prev").prop("disabled", currentPage <= 0);
        $(".btn-next").prop("disabled", currentPage >= totalPages - 1);
    }

// 添加跳转函数
function goToEvaluation(orderId, description, createdAt,status) {

    if(status==='已完成'){
        window.location.href = "<%=request.getContextPath()%>/repair/repair_evaluationAdd.jsp?" +
            "orderId=" + orderId +
            "&description=" + encodeURIComponent(description) +
            "&createdAt=" + encodeURIComponent(createdAt);
    }else if(status==='已撤回'){
        alert("该报修单已撤回，无法评价");
    }else if(status==='处理中'){
        alert("该报修单尚未处理，无法评价");
    }

}

    // 添加跳转函数
    function viewRepairProgress(orderId, roomNumber, createdAt,processAt,completedAt, description, status) {
        // URL encode the parameters to handle special characters
        var encodedDescription = description;
        var encodedCreatedAt = createdAt;
        var encodedProcessAt = processAt;
        var encodedCompletedAt = completedAt;
        var encodedStatus = status;
        console.log(encodedStatus)
        
        window.location.href = "<%=request.getContextPath()%>/repair/repair_progress.jsp?" +
            "orderId=" + orderId + 
            "&roomNumber=" + roomNumber + 
            "&createdAt=" + encodedCreatedAt +
            "&processAt=" + encodedProcessAt +
            "&completedAt=" + encodedCompletedAt +
            "&description=" + encodedDescription+
            "&status=" + encodedStatus;
    }


   // 修改处理按钮点击事件
$(document).on('click', '.process-btn', function() {
    // 获取当前行的报修单号（第一列的值）
    var orderId = $(this).closest('tr').find('td:first').text();
    var currentRow = $(this).closest('tr');
    
    if(confirm('确定要处理该报修单吗？')) {
        $.post("<%=request.getContextPath()%>/repairController", 
            {op: "process", orderId: orderId},
            function(response) {
                try {
                    var data = typeof response === 'string' ? JSON.parse(response) : response;
                    if(data.success) {
                        alert("处理状态已更新");
                        currentRow.find('td:eq(5)').text('处理中')
                            .removeClass('status-pending status-completed')
                            .addClass('status-processing');
                        // 刷新页面数据
                        loadData(currentPage);
                    } else {
                        alert("更新失败: " + (data.message || '未知错误'));
                    }
                } catch(e) {
                    alert("请求失败: 服务器返回数据格式错误");
                }
            }
        ).fail(function() {
            alert("请求失败，请检查网络连接");
        });
    }
});

    // 修改撤回按钮点击事件
    $(document).on('click', '.withdraw-btn', function () {
        var orderId = $(this).closest('tr').find('td:eq(0)').text();
        var currentRow = $(this).closest('tr');

        if (confirm('确定要撤回该报修单吗？')) {
            $.post("<%=request.getContextPath()%>/repairController",
                {op: "withdraw", orderId: orderId},
                function (response) {
                    try {
                        var data = typeof response === 'string' ? JSON.parse(response) : response;
                        if (data.success) {
                            alert("撤回成功");
                            // 更新状态为已撤回
                            currentRow.find('td:eq(5)').text('已撤回')
                                .removeClass('status-pending status-processing status-completed')
                                .addClass('status-withdrawn');
                            // 清空操作栏
                            currentRow.find('td:eq(6) .action-buttons').html('');
                        } else {
                            alert("撤回失败: " + (data.message || '未知错误'));
                        }
                    } catch (e) {
                        alert("请求失败: 服务器返回数据格式错误");
                    }
                }
            ).fail(function () {
                alert("请求失败，请检查网络连接");
            });
        }
    });


    // 添加完成按钮点击事件
    $(document).on('click', '.complete-btn', function() {
        var orderId = $(this).closest('tr').find('td:eq(0)').text();
        var currentRow = $(this).closest('tr');

        if(confirm('确定要完成该报修单吗？')) {
            $.post("<%=request.getContextPath()%>/repairController",
                {op: "complete", orderId: orderId},
                function(response) {
                    try {
                        var data = typeof response === 'string' ? JSON.parse(response) : response;
                        if(data.success) {
                            alert("完成状态已更新");
                            currentRow.find('td:eq(5)').text('已完成')
                                .removeClass('status-pending status-processing')
                                .addClass('status-completed');
                            // 清空操作栏
                            currentRow.find('td:eq(6) .action-buttons').html('');
                        } else {
                            alert("更新失败: " + (data.message || '未知错误'));
                        }
                    } catch(e) {
                        alert("请求失败: 服务器返回数据格式错误");
                    }
                }
            ).fail(function() {
                alert("请求失败，请检查网络连接");
            });
        }
    });

// 提交新增报修表单
function submitRepair() {
    var formData = {
        roomNumber: $('#modalRoomNumber').val(),
        name: $('#modalName').val(),
        description: $('#modalDescription').val(),
        op: "add"
    };
    
    if (!formData.roomNumber || !formData.name || !formData.description) {
        alert("请填写所有必填字段");
        return;
    }

    $.post("<%=request.getContextPath()%>/repairController", 
        formData,
        function(response) {
            try {
                var data = typeof response === 'string' ? JSON.parse(response) : response;
                if(data.success) {
                    alert("报修单提交成功");
                    closeModal();
                    loadData(currentPage); // 刷新列表
                } else {
                    alert("提交失败: " + (data.message || '未知错误'));
                }
            } catch(e) {
                alert("请求失败: 服务器返回数据格式错误");
            }
        }
    ).fail(function() {
        alert("请求失败，请检查网络连接");
    });
}

    // 页面加载时初始化数据
    $(document).ready(function () {
        loadData(0);
    });

    // 打开新增报修模态框
    function openAddRepairModal() {
        $('#addRepairModal').show();
    }

    // 关闭新增报修模态框
    function closeAddRepairModal() {
        $('#addRepairModal').hide();
        $('#addRepairForm')[0].reset();
    }

    // 修改新增按钮点击事件
    $('.add-btn').click(function (e) {
        e.preventDefault(); // 阻止默认行为
        $('#repairModal').show(); // 显示模态框
    });

    // 关闭模态框函数
    function closeModal() {
        $('#repairModal').hide();
        $('#repairForm')[0].reset();
    }

    function submitRepair() {
        var formData = {
            roomNumber: $('#modalRoomNumber').val(),
            name: $('#modalName').val(),
            description: $('#modalDescription').val(),
            op: "add"
        };
        $.get("<%=request.getContextPath()%>/repairController", formData, function (data) {
            if (data == "宿舍号和报修人不匹配") {
                alert(data)
            } else {
                alert(data);
                closeModal();
                loadData(); // 刷新数据
            }
        })
    }
    
</script>
</body>
</html>


<style>
    /* 新增模态框样式 - 优化版 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        animation: fadeIn 0.3s;
    }

    .modal-content {
        background-color: #fff;
        margin: 8% auto;
        padding: 25px;
        border: none;
        width: 450px;
        border-radius: 8px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: #2196F3;
    }

    .close {
        color: #aaa;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        transition: color 0.3s;
    }

    .close:hover {
        color: #333;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
        color: #555;
    }

    .form-group input,
    .form-group textarea {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
    }

    .form-group textarea {
        height: 100px;
        resize: vertical;
    }

    .form-group input:focus,
    .form-group textarea:focus {
        border-color: #2196F3;
        outline: none;
    }

    .submit-btn {
        background-color: #2196F3;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: background-color 0.3s;
        width: 100%;
    }

    .submit-btn:hover {
        background-color: #0b7dda;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
        }
        to {
            opacity: 1;
        }
    }
</style>
